package main

/*******************************************************************************
Copyright:cloud
Author:cloudapex@126.com
Version:1.0
Date:2019-3-12
Description: 程序入口
*******************************************************************************/
import (
	"flag"
	"fmt"
	"os"
	"time"

	"permis/conf"
	_ "permis/server"

	"gitee.com/cloudapex/ulern/cto"
	"gitee.com/cloudapex/ulern/htp"
	"gitee.com/cloudapex/ulern/util"
	"github.com/kardianos/service"
)

const (
	DEF_APP_MAJOR  = 1          // 主版本号
	DEF_APP_MINOR  = 2          // 次版本号
	DEF_APP_REVISE = 11         // 修订版本号
	DEF_APP_NAME   = "m_permis" // 应用名称
	DEF_APP_TITLE  = "权限管理服务"   // 应用显示名称
)

var config = ""
var logConf util.LogConf
var ver = fmt.Sprintf("%d.%d.%d", DEF_APP_MAJOR, DEF_APP_MINOR, DEF_APP_REVISE)

func init() {
	flag.IntVar((*int)(&logConf.Level), "logLv", int(util.ELL_Debug), "Main logger level[1:LL_DEBUG]")
	flag.IntVar((*int)(&logConf.OutMode), "logMode", int(util.ELM_Std|util.ELM_File), "Main logger outMode[std|file]")
	flag.StringVar(&logConf.DirName, "logDir", "./logs", "Main log dir name[logs]")
	flag.StringVar(&logConf.FileName, "logFile", "", "Main log file name[same as exe]")
	flag.StringVar(&logConf.FileSuffix, "logSuffix", "", "Main log file suffix[log]")
	flag.StringVar(&config, "conf", DEF_APP_NAME, "Main config file name")
}

type program struct{}

func (p *program) Init() bool {
	if len(os.Args) > 1 && (os.Args[1] == "-I" || os.Args[1] == "-U" || os.Args[1] == "-S") {
		svcConfig := &service.Config{
			Name:        DEF_APP_NAME,                                                           //服务显示名称
			DisplayName: DEF_APP_TITLE,                                                          //服务名称
			Description: fmt.Sprintf("This is an YuXue %s server of Go service.", DEF_APP_NAME), //服务描述
			Arguments:   []string{"-S", "-logLv=2", "-logMode=2"},
		}

		s, err := service.New(&program{}, svcConfig)
		if err != nil {
			util.Print("err:%v", err)
			return false
		}

		switch os.Args[1] {
		case "-I":
			if err = s.Install(); err != nil {
				util.Print("Service Installation err:%v.", err)
			} else {
				util.Print("Service Installation successful.")
			}
		case "-U":
			if err = s.Uninstall(); err != nil {
				util.Print("Service Installation err:%v.", err)
			} else {
				util.Print("Service uninstallation successful.")
			}
		case "-S":
			if err = s.Run(); err != nil {
				util.Print("Service Run err:%v", err)
			}
		}
		return false
	}
	return true
}
func (p *program) Start(s service.Service) error {
	go p.Work(report)
	return nil
}
func (p *program) Stop(s service.Service) error {
	util.Quit()
	return nil
}
func (p *program) Work(report func(msg string)) {
	util.Init(&logConf)

	conf.Main.Path(config)
	cto.Report(util.ELL_Error, report)

	defer func() { util.Catch("Main", recover(), true) }()

	util.Log.Info("[%q][%q|%q] Start...", util.ExeName(), ver, util.UTD_VERSION)
	if err := cto.Work(); err != nil {
		util.Log.Fatal("Start Work error:%q.", err)
	}
	util.Log.Info("[%q][%q|%q] running...", util.ExeName(), ver, util.UTD_VERSION)

	time.Sleep(time.Second * 1)
	util.Wait()
}

func main() {
	if prg := (&program{}); prg.Init() {
		prg.Work(report)
	}
}

func report(msg string) {
	if !conf.Main.Report().Enable {
		return
	}

	content := fmt.Sprintf("[**%s**: 服务名:%q 程序名:<font color=\"info\">%q</font> 版本:%q]\n>%s",
		conf.Main.Report().Env, DEF_APP_TITLE, util.ExeName(), ver, msg)
	bBody, err := cto.NewReportMarkdown(content, "18530926135")
	if err != nil || len(bBody) == 0 {
		return
	}

	htp.HttpRequest("POST", conf.Main.Report().ToAddr, string(bBody), nil)
}
